package com.example.framework.security.core.resolver;

import com.example.framework.security.core.LoginUser;
import com.example.framework.security.core.annotation.LoggedInUser;
import com.example.framework.security.core.util.JwtTokenUtils;
import com.example.framework.web.core.util.WebFrameworkUtils;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 解析有@LoginUser注解的方法参数，通过请求attribute的userId查询用户信息，注入UserDto
 */
@Component
@RequiredArgsConstructor
public class LoginUserHandlerMethodArgument implements HandlerMethodArgumentResolver {

    private final JwtTokenUtils jwtTokenUtils;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(LoginUser.class) && parameter.hasParameterAnnotation(LoggedInUser.class);
    }

    @Override
    public LoginUser resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer, @NotNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        String loginUserId = WebFrameworkUtils.getLoginUserId();
        if (!ObjectUtils.isEmpty(loginUserId)) {
            return jwtTokenUtils.getUserInfoFromCacheByUserId(loginUserId);
        }
        return null;
    }
}
